package com.sad.jetpack.v1.datamodel.demo.testFuture;

import android.content.ContentValues;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;
import android.util.Base64;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;

public class DataUtils {


    /**
     * 拆分集合
     * @param datas
     * @param splitSize
     * @param <T>
     * @return
     */
    public static  <T> List<List<T>> spliceArrays(List<T> datas,  int  splitSize) {
        if  (datas ==  null  || splitSize <  1 ) {
            return   null ;
        }
        int  totalSize = datas.size();
        //获取要拆分子数组个数
        int  count = (totalSize % splitSize ==  0 ) ?
                (totalSize / splitSize) : (totalSize/splitSize+ 1 );

        //System.out.println( "split count = "  +count);

        List<List<T>> rows =  new  ArrayList();
        for  ( int  i =  0 ;i < count;i ++) {

            int  index = i * splitSize;
            List<T> cols =  new  ArrayList();
            int  j =  0 ;
            while  (j < splitSize && index < totalSize) {
                cols.add(datas.get(index++));
                j ++;
            }
            rows.add(cols);
        }
        return  rows;
    }

    public static boolean isWifi(Context mContext) {
        ConnectivityManager connectivityManager = (ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetInfo != null
                && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            return true;
        }
        return false;
    }


    /**
     * 十六进制
     *
     * @param buffer
     * @return
     */
    public static String getMessageDigest(byte[] buffer) {
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");//MessageDigest.getInstance(Algorithm.MD5.getType());
            mdTemp.update(buffer);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char[] str = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * @param buffer
     * @return
     */
    public static byte[] getRawDigest(byte[] buffer) {
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");//MessageDigest.getInstance(Algorithm.MD5.getType());
            mdTemp.update(buffer);
            return mdTemp.digest();

        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 文件md5
     *
     * @param file
     * @return
     */
    public static String EncodeToMD5(final File file) {
        return EncodeToMD5(file, 1024 * 100);
    }
    private static String EncodeToMD5(final File file, final int bufLen) {
        if (file == null || bufLen <= 0 || !file.exists()) {
            return null;
        }

        FileInputStream fin = null;
        try {
            fin = new FileInputStream(file);
            String md5 = EncodeToMD5(fin, (int) (bufLen <= file.length() ? bufLen : file.length()));
            fin.close();
            return md5;

        } catch (Exception e) {
            return null;

        } finally {
            try {
                if (fin != null) {
                    fin.close();
                }
            } catch (IOException e) {

            }
        }
    }
    public static String EncodeToMD5(final InputStream is, final int bufLen) {
        if (is == null || bufLen <= 0) {
            return null;
        }
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");//MessageDigest.getInstance(Algorithm.MD5.getType());
            StringBuilder md5Str = new StringBuilder(32);

            byte[] buf = new byte[bufLen];
            int readCount = 0;
            while ((readCount = is.read(buf)) != -1) {
                md.update(buf, 0, readCount);
            }

            byte[] hashValue = md.digest();

            for (int i = 0; i < hashValue.length; i++) {
                md5Str.append(Integer.toString((hashValue[i] & 0xff) + 0x100, 16).substring(1));
            }
            return md5Str.toString();
        } catch (Exception e) {
            return null;
        }
    }

	public static String EncodeToMD5(byte[] btInput){
		char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
        try {
            //byte[] btInput = s.getBytes();
            // 获得MD5摘要算法�?MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘�?
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 判断对象或对象数组中每一个对象是否为空: 对象为null，字符序列长度为0，集合类、Map为empty
     *
     * @param obj
     * @return
     */
    public static boolean isNullOrEmpty(Object obj) {
        //Log.d( "obj--->"+obj);

        if (obj != null) {
            //Log.d("--->not null");
        } else {
            return true;
        }


        if (!obj.equals(null)) {
            //Log.d("--->not null");
        } else {
            return true;
        }

        if (obj.toString() != null) {//判断对象（不知道对不对）
            //Log.d("--->not null");
        } else {
            return true;
        }

        if ("".equals(obj) || "".equals(obj.toString())) {
            return true;
        }

        if (obj instanceof CharSequence) {
            //Log.d("--->CharSequence");
            return ((CharSequence) obj).length() == 0;
        }
        if (obj instanceof Collection) {
            //Log.d("--->Collection");
            return ((Collection) obj).isEmpty();
        }

        if (obj instanceof Map) {
            //Log.d( "--->Map");
            return ((Map) obj).isEmpty();
        }

        if (obj instanceof Object[]) {
            //Log.d("--->Object[]");
            Object[] object = (Object[]) obj;
            if (object.length == 0) {
                return true;
            }
            boolean empty = true;
            for (int i = 0; i < object.length; i++) {
                if (!isNullOrEmpty(object[i])) {
                    empty = false;
                    break;
                }
            }
            return empty;
        }

        if (obj instanceof JSONArray) {
            if (((JSONArray) obj).length() == 0) {
                return true;
            }
        }

        if (obj instanceof JSONObject) {
            if (((JSONObject) obj).length() == 0) {
                return true;
            }
        }

        return false;
    }

    //^((13[0-9])|(15[^4,//D])|(18[0,5-9])|(17[0,5-9]))//d{8}$
    public static boolean isMobileNO(String mobiles) {
        Pattern p = Pattern.compile("[1][23456789]\\d{9}");
        Matcher m = p.matcher(mobiles);
        //System.out.println(m.matches() + "---"+mobiles);
        return m.matches();
    }

    public static String friendlyCount(Long count) {
        return friendlyCount(count, 4);
    }

    public static String friendlyCount(Long count, int len) {

        if (DataUtils.isNullOrEmpty(count)) {
            return "0";
        }
        if (count < 10000 || (count + "").length() <= len) {
            return count + "";
        }
        String[] des = {"", "十", "百", "千", "万", "十万", "百万", "千万", "亿"};
        DecimalFormat df = new DecimalFormat("0.0");
        long s = Math.round(Math.pow(10, len));
        float v = (float) count / s;
        return df.format(v) + des[len]+"+";
		/*String[] des={"","十","百","千","万","十万","百万","千万","亿"};

		if (len<4 || len>8) {
			return count+"";
		}
		
		if (count==null) {
			return "0";
		}
		else{
			
			String cs=""+count;
			if(cs.length()>len){
				long s= Math.round(Math.pow(10,len));
				String d=des[len];
				String d2=des[len-1];
				long w=count/(s);
				long w_f=count%s;
				if(w_f>(s/2)){
					//float cf=Float.parseFloat(cs);
					//float cf_s=cf/s;					
					//return new java.text.DecimalFormat("#.0").format(cf_s)+"万+";
					long q=w_f/(s/10);
					return w+d+q+d2+"+";
				}
				else{
					return w+d+"+";
				}
				
			}
			else{
				return cs;
			}
		}*/
    }

    private static final int STRING_BUFFER_LENGTH = 100;

    public static long sizeOfString(final String str, String charset) throws UnsupportedEncodingException {
        if (TextUtils.isEmpty(str)) {
            return 0;
        }
        int len = str.length();
        if (len < STRING_BUFFER_LENGTH) {
            return str.getBytes(charset).length;
        }
        long size = 0;
        for (int i = 0; i < len; i += STRING_BUFFER_LENGTH) {
            int end = i + STRING_BUFFER_LENGTH;
            end = end < len ? end : len;
            String temp = getSubString(str, i, end);
            size += temp.getBytes(charset).length;
        }
        return size;
    }

    public static byte[] encryptSHA(byte[] data) throws Exception {
        MessageDigest sha = MessageDigest.getInstance(Algorithm.SHA.getType());
        sha.update(data);
        return sha.digest();
    }

    /**
     * 初始化HMAC密钥
     *
     * @param algorithm 算法，可为空。默认为：Algorithm.Hmac_MD5
     * @return
     * @throws Exception
     */
    public static String initMacKey(Algorithm algorithm) throws Exception {
        if (algorithm == null) algorithm = Algorithm.Hmac_MD5;
        KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm.getType());
        SecretKey secretKey = keyGenerator.generateKey();

        return base64Encoder(secretKey.getEncoded());//BASE64.encodeToString(secretKey.getEncoded());
    }

    /**
     * HMAC加密
     *
     * @param plain     明文
     * @param key       key
     * @param algorithm 算法，可为空。默认为：Algorithm.Hmac_MD5
     * @return
     * @throws Exception
     */
    public static byte[] encryptHMAC(byte[] plain, String key, Algorithm algorithm) throws Exception {
        if (algorithm == null) algorithm = Algorithm.Hmac_MD5;
        SecretKey secretKey = new SecretKeySpec(base64DecoderToBytes(key), algorithm.getType());
        Mac mac = Mac.getInstance(secretKey.getAlgorithm());
        mac.init(secretKey);

        return mac.doFinal(plain);
    }

    // get the sub string for large string
    public static String getSubString(final String str, int start, int end) {
        return new String(str.substring(start, end));
    }

    public static String base64Encoder(String str) {
        byte[] b = str.getBytes();
        return Base64.encodeToString(b, 0x0);
    }

    public static String base64Encoder(byte[] b) {
        return Base64.encodeToString(b, 0x0);
    }

    public static String base64Decoder(String str) {
        byte[] b = Base64.decode(str, Base64.DEFAULT);
        String s = new String(b);
        return s;
    }

    public static byte[] base64DecoderToBytes(String str) {
        byte[] b = Base64.decode(str, Base64.DEFAULT);
        return b;
    }

    /**
     * 判断是不是一个合法的电子邮件地址
     *
     * @param email
     * @return
     */
    public static boolean isEmail(String email) {
        Pattern emailer = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
        if (email == null || email.trim().length() == 0)
            return false;
        return emailer.matcher(email).matches();
    }

    /**
     * 将字符串分割成List
     *
     * @param str
     * @param k
     * @return
     */
    public static ArrayList<String> splitStr2list(String str, String k) {
        String[] arr = str.split(k);
        if (arr.length == 1 && "".equals(arr[0])) {
            return new ArrayList<String>();
        } else {
            System.out.println("-----/" + str);
            return new ArrayList<String>(Arrays.asList(arr));
        }
    }

    public static String list2splitStr(List<String> list, String k) {
        String str = "";
        for (String a : list) {
            String temp = "";
            if (list.indexOf(a) != list.size() - 1) {
                temp = k;
            }
            str += a + temp;
        }
        return str;
    }


    /**
     * 换算单位
     *
     * @param size
     * @return
     */
    public static String TransSize(long size) {
        String t_size = "";
        int b = 1024;
        int k = 1024 * 1024;
        int m = 1024 * 1024 * 1024;
        int g = 1024 * 1024 * 1024 * 1024;
        int t = 1024 * 1024 * 1024 * 1024 * 1024;
        int intSize = (int) size;
        if (intSize < b) {
            t_size = intSize + "B";
        } else if (intSize < k && intSize >= b) {
            t_size = M2((intSize * 1.00) / (b * 1.00)) + "KB";
        } else if (intSize < m && intSize >= k) {
            t_size = M2((intSize * 1.00) / (k * 1.00)) + "MB";
        } else if (intSize < g && intSize >= m) {
            t_size = M2((intSize * 1.00) / (m * 1.00)) + "GB";
        } else if (intSize >= g) {
            t_size = M2((intSize * 1.00) / (g * 1.00)) + "TB";
        }
        return t_size;
    }

    public static double M2(Double d) {
        BigDecimal b = new BigDecimal(d);
        double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        return f1;
    }

    /**
     * 数组转化为list
     *
     * @param arr
     * @return
     */
    public static <T> ArrayList<T> Arr2List(T[] arr) {
        List<T> list = Arrays.asList(arr);
        ArrayList<T> a = new ArrayList<T>(list);
        return a;
    }

    /**
     * 通过Gson将jsonArray转化成list
     *
     * @param j
     * @return
     */
    public static <T> ArrayList<T> JSONArray2List(JSONArray j) {
        Gson g = new Gson();
        ArrayList<T> list = g.fromJson(j.toString(), new TypeToken<ArrayList<T>>() {
        }.getType());
        return list;
    }

    /**
     * 通过Gson将jsonArray转化成array
     *
     * @param j
     * @return
     */
    public static <T> T[] JSONArray2Array(JSONArray j) {
        Gson g = new Gson();
        T[] ta = g.fromJson(j.toString(), new TypeToken<T[]>() {
        }.getType());
        return ta;
    }

    /**
     * HashMap转换ContentValues
     *
     * @param data
     * @return
     */
    public static ContentValues HM2CV(HashMap<String, String> data) {
        ContentValues values = new ContentValues();
        Iterator iter = data.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            values.put(entry.getKey().toString(), entry.getValue().toString());
        }
        return values;
    }

    /**
     * 是否是一个合法的url
     *此方法有问题，弃用
     * @param s
     * @return
     */
    @Deprecated
    public static boolean isURL(String s) {
        Pattern pattern = Pattern
                .compile("^([hH][tT]{2}[pP]://|[hH][tT]{2}[pP][sS]://)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\/])+$");
        return pattern.matcher(s).matches();
    }

    /**
     * 生成随机数
     *
     * @author Administrator
     */
    public static class Random {
        public static final String NUMBERS_AND_LETTERS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        public static final String NUMBERS = "0123456789";
        public static final String LETTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        public static final String CAPITAL_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        public static final String LOWER_CASE_LETTERS = "abcdefghijklmnopqrstuvwxyz";

        public static String getRandomNumbersAndLetters(int length) {
            return getRandom(NUMBERS_AND_LETTERS, length);
        }

        public static String getRandomNumbers(int length) {
            return getRandom(NUMBERS, length);
        }

        public static String getRandomLetters(int length) {
            return getRandom(LETTERS, length);
        }

        public static String getRandomCapitalLetters(int length) {
            return getRandom(CAPITAL_LETTERS, length);
        }

        public static String getRandomLowerCaseLetters(int length) {
            return getRandom(LOWER_CASE_LETTERS, length);
        }

        public static String getRandom(String source, int length) {
            return TextUtils.isEmpty(source) ? null : getRandom(source.toCharArray(), length);
        }

        public static String getRandom(char[] sourceChar, int length) {
            if (sourceChar == null || sourceChar.length == 0 || length < 0) {
                return null;
            }

            StringBuilder str = new StringBuilder(length);
            java.util.Random random = new java.util.Random();
            for (int i = 0; i < length; i++) {
                str.append(sourceChar[random.nextInt(sourceChar.length)]);
            }
            return str.toString();
        }

        public static int getRandom(int max) {
            return getRandom(0, max);
        }

        public static int getRandom(int min, int max) {
            if (min > max) {
                return 0;
            }
            if (min == max) {
                return min;
            }
            return min + new java.util.Random().nextInt(max - min);
        }
    }

    public enum Algorithm {
        SHA("SHA"),
        MD5("MD5"),
        Hmac_MD5("HmacMD5"),
        Hmac_SHA1("HmacSHA1"),
        Hmac_SHA256("HmacSHA256"),
        Hmac_SHA384("HmacSHA384"),
        Hmac_SHA512("HmacSHA512"),
        DES("DES"),
        RSA("RSA");

        private String type;

        Algorithm(String type) {
            this.type = type;
        }

        public String getType() {
            return type;
        }
    }

    public static class DES {

        /**
         * 转换秘钥
         *
         * @param key
         * @return
         * @throws Exception
         */
        private static Key toKey(byte[] key) throws Exception {
            DESKeySpec dks = new DESKeySpec(key);
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(Algorithm.DES.getType());
            SecretKey secretKey = keyFactory.generateSecret(dks);

            return secretKey;
        }

        /**
         * 解密
         *
         * @param plain
         * @param key
         * @return
         * @throws Exception
         */
        public static byte[] decrypt(byte[] plain, String key) throws Exception {
            Key k = toKey(base64DecoderToBytes(key));

            Cipher cipher = Cipher.getInstance(Algorithm.DES.getType());
            cipher.init(Cipher.DECRYPT_MODE, k);

            return cipher.doFinal(plain);
        }

        /**
         * 加密
         *
         * @param data
         * @param key
         * @return
         * @throws Exception
         */
        public static byte[] encrypt(byte[] data, String key) throws Exception {
            Key k = toKey(base64DecoderToBytes(key));
            Cipher cipher = Cipher.getInstance(Algorithm.DES.getType());
            cipher.init(Cipher.ENCRYPT_MODE, k);

            return cipher.doFinal(data);
        }

        /**
         * 生成密钥
         *
         * @return
         * @throws Exception
         */
        public static String initKey() throws Exception {
            return initKey(null);
        }

        /**
         * 生成密钥
         *
         * @param seed
         * @return
         * @throws Exception
         */
        public static String initKey(String seed) throws Exception {
            SecureRandom secureRandom = null;

            if (seed != null) {
                secureRandom = new SecureRandom(base64DecoderToBytes(seed));
            } else {
                secureRandom = new SecureRandom();
            }

            KeyGenerator kg = KeyGenerator.getInstance(Algorithm.DES.getType());
            kg.init(secureRandom);

            SecretKey secretKey = kg.generateKey();

            return base64Encoder(secretKey.getEncoded());
        }
    }


    public static class RSA {

        public static final String SIGNATURE_ALGORITHM = "MD5withRSA";

        private static final String PUBLIC_KEY = "RSAPublicKey";
        private static final String PRIVATE_KEY = "RSAPrivateKey";


        /**
         * 用私钥对信息生成数字签名
         *
         * @param data       加密数据
         * @param privateKey 私钥
         * @return
         * @throws Exception
         */
        public static String sign(byte[] data, String privateKey) throws Exception {
            byte[] keyBytes = base64DecoderToBytes(privateKey);        // 解密由base64编码的私钥
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);   // 构造PKCS8EncodedKeySpec对象
            KeyFactory keyFactory = KeyFactory.getInstance(Algorithm.RSA.getType());    // KEY_ALGORITHM 指定的加密算法
            PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);        // 取私钥匙对象
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);   // 用私钥对信息生成数字签名
            signature.initSign(priKey);
            signature.update(data);

            return base64Encoder(signature.sign());
        }

        /**
         * 校验数字签名
         *
         * @param data      加密数据
         * @param publicKey 公钥
         * @param sign      数字签名
         * @return
         * @throws Exception
         */
        public static boolean verify(byte[] data, String publicKey, String sign)
                throws Exception {

            byte[] keyBytes = base64DecoderToBytes(publicKey); // 解密由base64编码的公钥
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);  // 构造X509EncodedKeySpec对象
            KeyFactory keyFactory = KeyFactory.getInstance(Algorithm.RSA.getType());  // KEY_ALGORITHM 指定的加密算法
            PublicKey pubKey = keyFactory.generatePublic(keySpec);   // 取公钥对象

            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
            signature.initVerify(pubKey);
            signature.update(data);

            return signature.verify(base64DecoderToBytes(sign));
        }

        /**
         * 用私钥解密
         *
         * @param data
         * @param key
         * @return
         * @throws Exception
         */
        public static byte[] decryptByPrivateKey(byte[] data, String key)
                throws Exception {
            byte[] keyBytes = base64DecoderToBytes(key);   // 对密钥解密

            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);   // 取得私钥
            KeyFactory keyFactory = KeyFactory.getInstance(Algorithm.RSA.getType());
            Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);

            // 对数据解密
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, privateKey);

            return cipher.doFinal(data);
        }

        /**
         * 用公钥解密
         *
         * @param data
         * @param key
         * @return
         * @throws Exception
         */
        public static byte[] decryptByPublicKey(byte[] data, String key)
                throws Exception {
            byte[] keyBytes = base64DecoderToBytes(key);       // 对密钥解密

            // 取得公钥
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(Algorithm.RSA.getType());
            Key publicKey = keyFactory.generatePublic(x509KeySpec);

            // 对数据解密
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, publicKey);

            return cipher.doFinal(data);
        }

        /**
         * 用公钥加密
         *
         * @param data
         * @param key
         * @return
         * @throws Exception
         */
        public static byte[] encryptByPublicKey(byte[] data, String key)
                throws Exception {
            byte[] keyBytes = base64DecoderToBytes(key);   // 对公钥解密

            // 取得公钥
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(Algorithm.RSA.getType());
            Key publicKey = keyFactory.generatePublic(x509KeySpec);

            // 对数据加密
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);

            return cipher.doFinal(data);
        }

        /**
         * 用私钥加密
         *
         * @param data
         * @param key
         * @return
         * @throws Exception
         */
        public static byte[] encryptByPrivateKey(byte[] data, String key)
                throws Exception {

            byte[] keyBytes = base64DecoderToBytes(key);   // 对密钥解密

            // 取得私钥
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(Algorithm.RSA.getType());
            Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);

            // 对数据加密
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);

            return cipher.doFinal(data);
        }

        /**
         * 取得私钥
         *
         * @param keyMap
         * @return
         * @throws Exception
         */
        public static String getPrivateKey(Map<String, Object> keyMap)
                throws Exception {
            Key key = (Key) keyMap.get(PRIVATE_KEY);

            return base64Encoder(key.getEncoded());
        }

        /**
         * 取得公钥
         *
         * @param keyMap
         * @return
         * @throws Exception
         */
        public static String getPublicKey(Map<String, Object> keyMap)
                throws Exception {
            Key key = (Key) keyMap.get(PUBLIC_KEY);

            return base64Encoder(key.getEncoded());
        }

        /**
         * 初始化密钥
         *
         * @return
         * @throws Exception
         */
        public static Map<String, Object> initKey() throws Exception {
            KeyPairGenerator keyPairGen = KeyPairGenerator
                    .getInstance(Algorithm.RSA.getType());
            keyPairGen.initialize(1024);

            KeyPair keyPair = keyPairGen.generateKeyPair();
            RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();    // 公钥
            RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();     // 私钥
            Map<String, Object> keyMap = new HashMap<String, Object>(2);

            keyMap.put(PUBLIC_KEY, publicKey);
            keyMap.put(PRIVATE_KEY, privateKey);
            return keyMap;
        }

    }


    /* public static long force2long(Integer i){

         String is=i+"";
         Long l=force2long(is);
         return l;
     }*/
    public static long force2long(Object i) {
        //LogPrinterUtils.e("------------->i="+i);
        String is = i + "";
        try {
            Long l = Long.parseLong(is);
            return l;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        } catch (Error ee) {
            ee.printStackTrace();
            return 0;
        }

    }

    public static boolean isGeneralizedUrl(String s) {
        return Pattern.matches("[a-zA-Z0-9_]+://(\\w*|\\W*|[\\u4e00-\\u9fa5]*)*", s);
    }

}
